/**
 * Copyright (C) 2016 Hyphenate Inc. All rights reserved.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.hyphenate.easeui.ui;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.iwinding.ladygg.R;
import com.iwinding.ladygg.utils.AMMapHelper;

public class EaseBaiduMapActivity extends Activity {

    private final static String TAG = "map";
    static MapView mMapView = null;
    FrameLayout mMapViewContainer = null;
    AMapLocationClient mLocClient;
    public MyLocationListenner myListener = new MyLocationListenner();

    Button sendButton = null;

    EditText indexText = null;
    int index = 0;
    // LocationData locData = null;
    static AMapLocation lastLocation = null;
    public static EaseBaiduMapActivity instance = null;
    ProgressDialog progressDialog;
    private AMap mAMap;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        instance = this;
        //initialize SDK with context, should call this before setContentView
        setContentView(R.layout.ease_activity_baidumap);
        mMapView = (MapView) findViewById(R.id.bmapView);
        mMapView.onCreate(savedInstanceState);
        sendButton = (Button) findViewById(R.id.btn_location_send);
        Intent intent = getIntent();
        double latitude = intent.getDoubleExtra("latitude", 0);
        if (mAMap == null) {
            mAMap = mMapView.getMap();
        }
        mAMap.setMapType(AMap.MAP_TYPE_NORMAL);
        mAMap.setMaxZoomLevel(15.0f);
        mAMap.setMinZoomLevel(4.0f);
        initMapView();
        if (latitude == 0) {
            double longtitude = intent.getDoubleExtra("longitude", 0);
            mMapView = new MapView(this);
            MyLocationStyle myLocationStyle = new MyLocationStyle()
                    .myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE)
                    .anchor((float) latitude, (float) longtitude)
                    .showMyLocation(true);
            mAMap.setMyLocationStyle(myLocationStyle);
            showMapWithLocationClient();
        } else {
            double longtitude = intent.getDoubleExtra("longitude", 0);
            String address = intent.getStringExtra("address");
            mMapView = new MapView(this);
            showMap(latitude, longtitude, address);
        }
    }

    private void showMap(double latitude, double longtitude, String address) {
        sendButton.setVisibility(View.GONE);
        mAMap.setMaxZoomLevel(17.0f);
        mAMap.setMinZoomLevel(4.0f);
        MyLocationStyle myLocationStyle = new MyLocationStyle()
                .myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE)
                .anchor((float) latitude, (float) longtitude)
                .showMyLocation(true);
        mAMap.setMyLocationStyle(myLocationStyle);
        mAMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longtitude), 17));
        mAMap.clear();
        MarkerOptions markerOption = new MarkerOptions();
        markerOption.position(new LatLng(latitude,
                longtitude));
        markerOption.title(address);
        markerOption.visible(true);
        Marker marker = mAMap.addMarker(markerOption);
    }

    private void showMapWithLocationClient() {
        String str1 = getResources().getString(R.string.Making_sure_your_location);
        progressDialog = new ProgressDialog(this);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage(str1);

        progressDialog.setOnCancelListener(new OnCancelListener() {

            public void onCancel(DialogInterface arg0) {
                if (progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
                Log.d("map", "cancel retrieve location");
                finish();
            }
        });

        progressDialog.show();

        mLocClient = new AMapLocationClient(this);
        mLocClient.setLocationListener(myListener);

        AMapLocationClientOption option = new AMapLocationClientOption();
        option.setOnceLocation(true);//可选，默认0，即仅定位一次
        option.setOnceLocationLatest(true);
        option.setNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
        option.setInterval(1000);
        option.setWifiActiveScan(false);//设置是否强制刷新WIFI

        option.setMockEnable(true);//设置是否允许模拟位置,默认为true，允许模拟位置
        option.setHttpTimeOut(20000);//定位请求超时时间
        option.setLocationCacheEnable(false);//关闭缓存机制
//        option.setGpsFirst(true);
        mLocClient.setLocationOption(option);
        mLocClient.stopLocation();
        mLocClient.startLocation();
    }

    @Override
    protected void onPause() {
        mMapView.onPause();
        if (mLocClient != null) {
            mLocClient.stopLocation();
        }
        super.onPause();
        lastLocation = null;
    }

    @Override
    protected void onResume() {
        mMapView.onResume();
        if (mLocClient != null) {
            mLocClient.startLocation();
        }
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        if (mLocClient != null)
            mLocClient.stopLocation();
        mMapView.onDestroy();
        super.onDestroy();
    }

    private void initMapView() {
        mMapView.setLongClickable(true);
    }

    /**
     * format new location to string and show on screen
     */
    public class MyLocationListenner implements AMapLocationListener {

        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            if (amapLocation == null) {
                return;
            }
            Log.d("map", "On location change received:" + amapLocation);
            Log.d("map", "addr:" + amapLocation.getAddress());
            sendButton.setEnabled(true);
            if (progressDialog != null) {
                progressDialog.dismiss();
            }
            if (amapLocation != null) {

                if (lastLocation != null) {
                    if (lastLocation.getLatitude() == amapLocation.getLatitude() && lastLocation.getLongitude() == amapLocation.getLongitude()) {
                        Log.d("map", "same location, skip refresh");
                        // mMapView.refresh(); //need this refresh?
                        return;
                    }
                }
                lastLocation = amapLocation;
                mAMap.clear();
                if (amapLocation.getErrorCode() == 0) {
                    //解析定位结果
                    int locType = amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                    switch (locType) {
                        case 1://GPS定位结果
                        case 2://前次定位结果
                        case 4://缓存定位结果
                        case 5://Wifi定位结果
                        case 6://基站定位结果
                        case 8://离线定位结果
                            showMap(amapLocation.getLatitude(), amapLocation.getLongitude(), amapLocation.getAddress());
                            sendButton.setVisibility(View.VISIBLE);
                            AMMapHelper.getInstance().setmLocationInfo(amapLocation);
                            break;
                    }
                }
            }
            if (mLocClient != null)
                mLocClient.stopLocation();
        }
    }

    ;

    public void back(View v) {
        finish();
    }

    public void sendLocation(View view) {
        if (lastLocation != null) {
            Intent intent = this.getIntent();
            intent.putExtra("latitude", lastLocation.getLatitude());
            intent.putExtra("longitude", lastLocation.getLongitude());
            intent.putExtra("address", lastLocation.getAddress());
            this.setResult(RESULT_OK, intent);
            finish();
            overridePendingTransition(R.anim.slide_in_from_left, R.anim.slide_out_to_right);
        } else {
            Toast.makeText(this, "获取不到地址", Toast.LENGTH_SHORT).show();
        }
    }

}
